﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Repository.cs" company="Oliver Kurowski">
//    (c) Oliver Kurowski. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace RegioKistl.Models.DataAccess
{
    using Raven.Client;
    using Raven.Client.Document;

    /// <summary>
    /// Encapsulates the access to the data storage.
    /// </summary>
    public static class Repository
    {
        /// <summary>
        /// The document store. This is a static instance that is thread-safe to access.
        /// </summary>
        private static IDocumentStore documentStore;

        /// <summary>
        /// Gets this instance.
        /// </summary>
        /// <returns>The document session. You must dispose the instance.</returns>
        public static IDocumentSession OpenSession()
        {
            var store = GetDocumentStore();

            return store.OpenSession();
        }

        /// <summary>
        /// Shutdowns this instance.
        /// </summary>
        public static void Shutdown()
        {
            if (documentStore == null)
            {
                return;
            }

            documentStore.Dispose();
            documentStore = null;
        }

        /// <summary>
        /// Gets the document store.
        /// </summary>
        /// <returns></returns>
        private static IDocumentStore GetDocumentStore()
        {
            if (documentStore != null)
            {
                return documentStore;
            }

            documentStore = new DocumentStore
                                {
                                    Url = "http://localhost:8080/",
                                    DefaultDatabase = "test"
                                };

            documentStore.Initialize();

            return documentStore;
        }
    }
}